import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { RouteRecordRaw } from 'vue-router'
import router, { constantRoutes, asyncRoutes } from '@/router'

// 判断用户是否有某个权限
const hasPermission = (permissionName: string, roles: string[]) => {
  return roles.includes(permissionName)
}
export const usePermissionStore = defineStore('permissionStore', () => {
  const roles = ref<string[]>([])
  const routes = ref<RouteRecordRaw[]>(constantRoutes)
  const routesData = computed(() => routes.value)

  // 获取用户权限
  const getUserPermission = () => {
    // 调用接口获取用户权限
    // 假设获取到的权限为 ['user', 'admin']
    const accessedRoutes: RouteRecordRaw[] = asyncRoutes
    // TODO: 将新的路由正确放入路有选项的children中
    for (const r of accessedRoutes) {
      if (r.meta?.parent) {
        router.addRoute(r.meta.parent as string, r)
      } else {
        router.addRoute(r)
      }
    }
    routes.value = accessedRoutes
    router.options.routes = constantRoutes.concat(accessedRoutes)

    roles.value = ['user', 'admin']
    return { roles, routes }
  }

  hasPermission('user', roles.value)
  return { roles, routesData, getUserPermission, hasPermission }
})
